package com.ulook.lookplanet.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.ulook.lookplanet.R;
import com.ulook.lookplanet.base.BaseFragment;
import com.ulook.lookplanet.common.ActivityCode;
import com.ulook.lookplanet.common.AppServer;
import com.ulook.lookplanet.data.model.BaseUser;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.data.model.Visitor;
import com.ulook.lookplanet.main.MainActivity;
import com.ulook.lookplanet.ui.home.login.LoginActivity;
import com.ulook.lookplanet.ui.home.modify.ModifyUserActivity;
import com.ulook.lookplanet.ui.home.my.MyArtActivity;
import com.ulook.lookplanet.util.StringUtil;
import com.ulook.lookplanet.widget.RoundImageView;

public class HomeFragment extends BaseFragment {

    private HomeViewModel homeViewModel;
    private View root;

    private RoundImageView head;
    private TextView username;
    private TextView level;
    private TextView planet;
    private TextView fans;
    private TextView con_topics;
    private TextView con_user;
    private TextView username2;
    private TextView id;
    private TextView age;
    private TextView gender;
    private TextView star_sign;
    private TextView city;
    private TextView hobby;
    private TextView signature;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // 获取ViewMode
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        // 获取布局资源
        root = inflater.inflate(R.layout.fragment_home, container, false);
        // 设置ToolBar
        Toolbar toolbar = root.findViewById(R.id.home_toolbar);
        toolbar.inflateMenu(R.menu.home_menu);
        // 设置菜单
        toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()){
                // 退出
                case R.id.bt_logout:
                    logout();
                    break;
                // 修改信息
                case R.id.bt_modify_user:
                    modify();
                    break;
                // 我的动态
                case R.id.bt_my_article:
                    myArticle();
                    break;
            }
            return false;
        });

        // 观察ViewMode
        homeViewModel.getToastText().observe(getViewLifecycleOwner(), toastText -> {
            Toast.makeText(getActivity(), toastText, Toast.LENGTH_SHORT).show();
        });
        homeViewModel.getUserInfo().observe(getViewLifecycleOwner(), vUserInfo -> {
            if(vUserInfo.getId() == 0){
                setVisitor(vUserInfo);      // 展示游客身份并显示登陆注册按钮
            }else{
                setUserInfoView(vUserInfo); // 展示用户信息
            }
        });

        // 初始化页面信息
        initUserInfo();


        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        root.findViewById(R.id.bt_login).setOnClickListener(view -> {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivityForResult(intent, ActivityCode.LOGIN_REQUEST);
        });
    }

    /**
     * 监听其他Activity的返回结果
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case ActivityCode.LOGIN_RESULT_OK :
                // 设置当前用户
                ((MainActivity)getActivity()).loginMode((BaseUser) data.getSerializableExtra("user"));
                initUserInfo(); // 重新初始化页面
                break;
            case ActivityCode.MOD_USER_RESULT_OK:
                // 更新用户信息
                TUser user = (TUser) data.getSerializableExtra("user");
                updateUserInfo(user);
                break;
            default : break;
        }
    }

    /**
     * 初始化用户信息界面
     */
    private void initUserInfo(){
        head = root.findViewById(R.id.head_img);
        head.setImageResource(R.mipmap.user_head_img);
        username = root.findViewById(R.id.user_name);
        username.setText(R.string.user_name);
        level = root.findViewById(R.id.level);
        level.setText(R.string.level);
        planet = root.findViewById(R.id.planet);
        planet.setText(R.string.user_planet);
        fans = root.findViewById(R.id.fans);
        fans.setText(R.string.fans);
        con_topics = root.findViewById(R.id.con_topics);
        con_topics.setText(R.string.con_topics);
        con_user = root.findViewById(R.id.con_user);
        con_user.setText(R.string.con_user);
        username2 = root.findViewById(R.id.user_name2);
        username2.setText(R.string.user_name2);
        id = root.findViewById(R.id.user_id);
        id.setText(R.string.user_id);
        age = root.findViewById(R.id.age);
        age.setText(R.string.age);
        gender = root.findViewById(R.id.gender);
        gender.setText(R.string.gender);
        star_sign = root.findViewById(R.id.star_sign);
        star_sign.setText(R.string.star_sign);
        city = root.findViewById(R.id.city);
        city.setText(R.string.city);
        hobby = root.findViewById(R.id.hobby);
        hobby.setText(R.string.hobby);
        signature = root.findViewById(R.id.signature);
        signature.setText(R.string.signature);
        // 获取MainActivity中的当前用户id
        BaseUser user = ((MainActivity)getActivity()).getCurrUser();
        if(user instanceof TUser){
            homeViewModel.initUserInfo(((TUser) user).getId());
        }else if(user instanceof Visitor){
            homeViewModel.initUserInfo(((Visitor) user).getId());
        }
    }

    /**
     * 展示游客身份并显示登陆注册按钮
     */
    private void setVisitor(VUserInfo visitor){
        TextView username2 = root.findViewById(R.id.user_name2);
        username2.setText(R.string.user_name2);
        username.setVisibility(View.GONE);
        root.findViewById(R.id.level_element).setVisibility(View.GONE);
        root.findViewById(R.id.concern).setVisibility(View.GONE);
        root.findViewById(R.id.bt_login).setVisibility(View.VISIBLE);
    }

    /**
     * 展示用户信息
     */
    private void setUserInfoView(VUserInfo vUserInfo){
        username.setVisibility(View.VISIBLE);
        root.findViewById(R.id.level_element).setVisibility(View.VISIBLE);
        root.findViewById(R.id.concern).setVisibility(View.VISIBLE);
        root.findViewById(R.id.bt_login).setVisibility(View.GONE);

        if(!"".equals(vUserInfo.getHeadimg()) && vUserInfo.getHeadimg() != null){
            head.setImageURL(AppServer.HEAD_IMG_PATH + vUserInfo.getHeadimg());
        }
        username.append(vUserInfo.getName());
        level.append(String.valueOf(vUserInfo.getLv()));
        planet.append(vUserInfo.getPlanetname());
        fans.append(String.valueOf(vUserInfo.getFans()));
        con_topics.append(String.valueOf(vUserInfo.getComus()));
        con_user.append(String.valueOf(vUserInfo.getCornusers()));
        username2.append(vUserInfo.getName());
        id.append(String.valueOf(vUserInfo.getId()));
        age.append(String.valueOf(vUserInfo.getAge()));
        gender.append(vUserInfo.getGender());
        star_sign.append(vUserInfo.getStarsign());
        city.append(vUserInfo.getCity());
        hobby.append(vUserInfo.getHobby());
        signature.append(vUserInfo.getSignature());
    }

    /**
     * 查看我发布的动态
     */
    private void myArticle(){
        Intent intent = new Intent(getActivity(), MyArtActivity.class);
        intent.putExtra("currUserId", homeViewModel.getUserInfo().getValue().getId());
        // 跳转修改页面
        startActivity(intent);
    }

    /**
     * 退出登陆
     */
    private void logout(){
        // 清除当前用户
        homeViewModel.logout();
        ((MainActivity)getActivity()).loginMode(new Visitor());
        // 跳转登录页面
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivityForResult(intent, ActivityCode.LOGIN_REQUEST);
    }

    /**
     * 修改信息
     */
    private void modify(){
        Intent intent = new Intent(getActivity(), ModifyUserActivity.class);
        intent.putExtra("currUserId", homeViewModel.getUserInfo().getValue().getId());
        // 跳转修改页面
        startActivityForResult(intent, ActivityCode.MOD_USER_REQUEST);
    }

    /**
     * 完成修改信息后更新页面
     */
    private void updateUserInfo(TUser user){
        if(user == null){
            return;
        }
        if(!StringUtil.isEmpty(user.getName())){
            username.setText(user.getName());
            username2.setText(getString(R.string.user_name2) + user.getName());
        }
        if(user.getAge() != 0){
            age.setText(getString(R.string.age) + user.getAge());
        }
        if(!StringUtil.isEmpty(user.getGender())){
            gender.setText(getString(R.string.gender) + user.getGender());
        }
        if(!StringUtil.isEmpty(user.getStarsign())){
            star_sign.setText(getString(R.string.star_sign) + user.getStarsign());
        }
        if(!StringUtil.isEmpty(user.getCity())){
            city.setText(getString(R.string.city) + user.getCity());
        }
        if(!StringUtil.isEmpty(user.getHobby())){
            hobby.setText(getString(R.string.hobby) + user.getHobby());
        }
        if(!StringUtil.isEmpty(user.getSignature())){
            signature.setText(getString(R.string.signature) + user.getSignature());
        }
        if(!StringUtil.isEmpty(user.getHeadimg())){
            head.setImageURL(AppServer.HEAD_IMG_PATH + user.getHeadimg());
        }
    }
}